﻿using GalaSoft.MvvmLight.Command;
using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.EAPClient.Common;
using Glorysoft.EAP.EAPClient.Model;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Windows;
using static Glorysoft.EAP.EAPClient.Model.SlotMap;

namespace Glorysoft.EAP.EAPClient.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class NeedleMarkDetectionViewModel : PopupWindowVM
    {
        private readonly Logger ServiceLogger = XfwContext.EapLogger;
        public delegate void CloseDelegate();
        public event CloseDelegate CloseEvent;
        List<SelectWaferInfo> maps = new List<SelectWaferInfo>();
        public C_LotInfo c_LotInfo = null;
        /// <summary>
        /// Initializes a new instance of the LoginViewModel class.
        /// </summary>
        public NeedleMarkDetectionViewModel()
        {
            AllWafersNeedleMark = new ObservableCollection<SLotMap>();// 取mes里的list

            var SelectWaferIdList = Dict.Current.SelectWaferIdList.TrimEnd(';');//1;2;3
            var Value = Dict.Current.TestModevalue;//选片模式
            if (Value == "Sequential")
            {
                foreach (var item in ClientInfo.EQPInfo.LotList[0].SlotMaps)
                {
                    if (item.waferState != WaferState.WaferNothing.ToString())
                    {
                        item.IsSelect = false;
                        AllWafersNeedleMark.Add(item);
                    }
                }
            }
            else if (Value == "Sample")
            {
                foreach (var item in ClientInfo.EQPInfo.LotList[0].SlotMaps)
                {
                    if (item.waferState != WaferState.WaferNothing.ToString())
                    {
                        if (SelectWaferIdList.Contains(item.slotId))
                        {
                            item.IsSelect = false;
                            AllWafersNeedleMark.Add(item);
                        }
                    }
                }
            }
            else if (Value == "Assign")//从指定位置测试
            {
                int begincount = Convert.ToInt32(SelectWaferIdList) - 1;
                int lastCount = ClientInfo.EQPInfo.LotList[0].SlotMaps.Count() - Convert.ToInt32(SelectWaferIdList) + 1;
                foreach (var item in ClientInfo.EQPInfo.LotList[0].SlotMaps.ToList().GetRange(begincount, lastCount))
                {
                    if (item.waferState != WaferState.WaferNothing.ToString())
                    {
                        item.IsSelect = false;
                        AllWafersNeedleMark.Add(item);
                    }
                }
            }
            c_LotInfo = new C_LotInfo();

            //test 使用
            //for (int i = 1; i <= 25; i++)
            //{
            //    AllWafers.Add(new SLotMap() {     SlotId = $"{i}",  WaferId = "1", isSelect = false });//eaf5fd
            //}
        }
        public Model.RunService ClientInfo
        {
            get
            {
                return Model.RunService.Current;
            }
        }
        private bool _isSelected = false;

        public bool IsSelected
        {
            get { return _isSelected; }

            set
            {
                _isSelected = value;
                RaisePropertyChanged("IsSelected");
            }
        }

        private ObservableCollection<SLotMap> allWafers = new ObservableCollection<SLotMap>();
        public ObservableCollection<SLotMap> AllWafersNeedleMark
        {
            get { return allWafers; }
            set
            {
                allWafers = value;
                RaisePropertyChanged("AllWafersNeedleMark");
            }
        }
        #region command
        private RelayCommand cancelCmd;
        public RelayCommand CancelCmd
        {
            get { return cancelCmd ?? (cancelCmd = new RelayCommand(Cancel)); }
        }
        public void Cancel()
        {
            try
            {
                if (CloseEvent != null)
                    CloseEvent();
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }

            this.Close();

            c_LotInfo.Clear();
            #region old Code
            ////ClientInfo.EQPInfo.LotList = new System.Collections.ObjectModel.ObservableCollection<C_LotInfo>();
            ////ClientInfo.EQPInfo.LotList.Add(new C_LotInfo() { UserId = USEID });
            // ClientInfo.EQPInfo.LotList[0].LotId = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].Qty = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].State = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].ProductId = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].ProberRecipe = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].TesterProgram = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].Probercard = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].LotsStatus = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].StageId = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].Priority = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].SlotMaps = null;
            // ClientInfo.EQPInfo.LotList[0].UNITLIST = null;
            //// ClientInfo.EQPInfo.BtnOk = Visibility.Visible;
            // if (ClientInfo.EQPInfo.LotList[0].UserId == null)
            // {
            //     ClientInfo.EQPInfo.BtnOk = Visibility.Collapsed;
            //     ClientInfo.EQPInfo.Btnclean = Visibility.Collapsed;
            // }
            // else
            // {
            //     ClientInfo.EQPInfo.BtnOk = Visibility.Visible;
            //     ClientInfo.EQPInfo.Btnclean = Visibility.Visible;
            // }
            #endregion

        }


        private RelayCommand confirmCmd;
        public RelayCommand ConfirmCmd
        {
            get { return confirmCmd ?? (confirmCmd = new RelayCommand(WaferConfirmCmd)); }
        }

        private RelayCommand cancelSelectNeedleMarkDetectionWaferId;
        public RelayCommand CancelSelectNeedleMarkDetectionWaferId
        {
            get { return cancelSelectNeedleMarkDetectionWaferId ?? (cancelSelectNeedleMarkDetectionWaferId = new RelayCommand(CancelSelectNeedleMarkDetection)); }
        }
        public class SelectWaferInfo
        {
            public string Slotid { get; set; }
            public string Waferid { get; set; }
        }

        private void WaferConfirmCmd()
        {
            var tempID = "";
            var mesid = "";

            var AllWaferList = AllWafersNeedleMark.Where(t => t.isSelect == true).ToList();
            var AllMESList = AllWafersNeedleMark.Where(t => t.WaferState == "WaferIn").ToList();
            foreach (var mesitem in AllMESList)
            {
                var itemslotid = mesitem.SlotId;
                mesid += itemslotid + ";";
            }
            foreach (var item in AllWaferList)//
            {
                var selectid = item.WaferId;
                var id = item.SlotId;
                tempID += id + ";";
                maps.Add(new SelectWaferInfo { Slotid = id, Waferid = selectid });
            }
            if (maps.Count == 0)
            {
                CMessageBox.Show("请选择自动针痕检测ID!");
                return;

            }
            else
            {
                Dictionary<string, string> messages = null;
                EAPClient eapclient = new EAPClient();
                //物料不一致时增加数量判断
                if (tempID.Split(";").Count() - 1 > mesid.Split(";").Count() - 1)
                {
                    CMessageBox.Show(Consts.GetTranslation("Msg_WaferIdInputInfoError"));
                    return;
                }
                else
                {
                    var result = eapclient.SelectNeedleMarkDetectionWaferId(tempID.TrimEnd(';'));
                    ServiceLogger.Debug($"选择针痕检测WaferId为:{tempID.TrimEnd(';')}");
                    if (result.ReturnCode == "0")
                    {
                        messages = TranslateMsg.GetTranslation("SelectNeedleMarkDetectionWaferIdOK", tempID);
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                        }
                        //  ClientInfo.EQPInfo.LotList[0].TestID = tempID.Replace(";", " ");  //前台显示测试的id ,id 之间用空格处理了
                    }
                    else
                    {
                        messages = TranslateMsg.GetTranslation("SelectNeedleMarkDetectionWaferIdNG");
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                        }
                    }
                    this.Close();
                }
            }
        }

        private void CancelSelectNeedleMarkDetection()
        {
            Dictionary<string, string> messages = null;
            EAPClient eapclient = new EAPClient();
            var result = eapclient.SelectNeedleMarkDetectionWaferId("");
            ServiceLogger.Debug($"选择针痕检测WaferId为:NULL");
            if (result.ReturnCode == "0")
            {
                messages = TranslateMsg.GetTranslation("CancelSelectNeedleMarkDetectionWaferIdOK", "0");
                if (!(messages == null || messages.Count == 0))
                {
                    ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                    XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                }
            }

            this.Close();
        }
        #endregion
    }
}